<?php


namespace app\common\model;

use think\facade\Cache;
use think\Model;

/**
 * 地区模型
 * @package app\common\model
 */
class Area extends Model
{
    protected $table = "ea_area";

    /**
     * 查询地区相关的数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getlist(): array
    {
        $map = Cache::get('area');
        if (!$map){
            $list = $this->field('area_id,area_no as value,area_name as label,parent_no')
                ->where('area_id','>',1)
                ->select()
                ->toArray();

            $map = [];

            // 查询省级数据
            foreach ($list as $key => $value) {
                if ($value['parent_no'] == -1) {
                    $map[] = $value;
                }
            }

            // 查询市区数据
            foreach ($map as $key => $value) {
                foreach ($list as $k => $v) {
                    if ($value['value'] == $v['parent_no']) {
                        $map[$key]['children'][] = $v;
                    }
                }
            }

            // 查询县区数据
            foreach ($map as $KK => $vv) {
                foreach ($vv['children'] as $key => $value) {
                    foreach ($list as $k => $v) {
                        if ($value['value'] == $v['parent_no']) {
                            $map[$KK]['children'][$key]['children'][] = $v;
                        }
                    }
                }
            }

            Cache::set('area',$map);
        }

        return $map;
    }
}
